// pages/todos/todos.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    search:'',
    listTodos:[{
      name:'Learning WEBAPP',
      completed:false
    },{
      name:'Learning Java',
      completed:true
    },{
      name:'Learning C++',
      completed:false
    }
  ],
  leftCount: 2,
  allCompleted: false
  },
  searchDate(e){
     
     this.setData({
       search:e.detail.value
     })
  },
  addTodoHandle(){
    //当按钮点击时
    if(!this.data.search)return;
  var todos=this.data.listTodos;
   todos.push({
      name:this.data.search,
      completed:false
    });
    this.setData({
      listTodos:todos,
      leftCount:this.data.leftCount+1,
      search:''
    })
  },
  taggleTodoHandle(e){
    // console.log(e.currentTarget.dataset.index);
    let item=this.data.listTodos[e.currentTarget.dataset.index];
    item.completed=!item.completed;
    var leftCount=this.data.leftCount+(item.completed?-1:1);
    this.setData({
      listTodos:this.data.listTodos,
      leftCount:leftCount
    })

  },
  removeTodosHandle(e){
    var num=e.currentTarget.dataset.index;
    var todos=this.data.listTodos;
    var leftCount=this.data.leftCount+(todos[num].completed ? 0 : -1);
    todos.splice(num,1)
    this.setData({
      listTodos: todos,
      leftCount: leftCount
    })
  },
  toggleAllHandle(){
    var todos=this.data.listTodos;
    var leftCount=this.data.leftCount;
    this.data.allCompleted=!this.data.allCompleted;
    var that=this;
    todos.forEach(element => {
      element.completed= that.data.allCompleted;
      leftCount=element.completed?0:todos.length;
    });
    this.setData({
      listTodos:todos,
      leftCount:leftCount
    })
  },
  clearAllHandle(){
    // var todos=[];
    // this.data.listTodos.forEach(element => {
    //   if(!element.completed){
    //     todos.push(element);
    //   }
    // });
    var todos=this.data.listTodos.filter(item => {
        return !item.completed;
    })
    this.setData({
      listTodos: todos
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})